package com.sodaopen.study.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.sodaopen.study.entity.Chapter;
import com.sodaopen.study.entity.Step;
import com.sodaopen.study.service.ChapterService;
import com.sodaopen.study.service.StepService;

@Controller
public class StepController {

	@Autowired
	private ChapterService chapterService;
	
	@Autowired
	private StepService stepService;

	@GetMapping("/content/step/add")
	public String addStep(Integer chapterId, Model model) {
		Chapter chapter = chapterService.findById(chapterId);
		model.addAttribute("chapter", chapter);
		
    	List<Step> list = stepService.findByChapterId(chapterId);
    	model.addAttribute("stepList", list);
		
		return "step-add";
	}

	
	
	@PostMapping("/content/step/add")
	public String saveStep(Step step, Model model) {
		System.out.println(step);
		if(step.getSort() == null){
			Integer maxSort = stepService.findMaxSort(step.getChapterId());
			step.setSort(maxSort+5);
		}
		stepService.saveStep(step);

		Chapter chapter = chapterService.findById(step.getChapterId());
		model.addAttribute("chapter", chapter);
		
    	List<Step> list = stepService.findByChapterId(step.getChapterId());
    	model.addAttribute("stepList", list);
		
		return "step-add";
	}

}
